package com.own.demo.geogrid;



import com.alibaba.fastjson.JSONObject;
import com.own.demo.utils.geo.PoiTypeEnums;
import com.own.demo.utils.geo.buffer.DefaultBufferImpl;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.grid.Grids;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.geometry.BoundingBox;

import java.awt.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
public class UtilsGeoGrid {

    /**
     *获取栅格化后的 Geometry 集合
     * @param srcGeometry    栅格前的 geometry
     * @param srcBoundingBox 栅格前的 boundingBox
     * @return 栅格化后的 BoundingBox 集合
     * @throws Exception 异常
     */
    public List<Geometry> gridGeometryInfo(Geometry srcGeometry, BoundingBox srcBoundingBox,boolean isIntersects, double sideLen) throws Exception {
        List<Geometry> geometries = new LinkedList<>();
        //获取 envelope
        ReferencedEnvelope envelope = getReferencedEnvelope(srcBoundingBox, sideLen);
        //栅格化
        SimpleFeatureSource grid = Grids.createSquareGrid(envelope, sideLen);
        SimpleFeatureCollection features = grid.getFeatures();
        SimpleFeatureIterator iterator = features.features();
        int i=0;
        while (iterator.hasNext()) {
            SimpleFeature feature = iterator.next();
            Geometry geometry = (Geometry) feature.getDefaultGeometry();
            if(isIntersects) {
                if (srcGeometry.intersects(geometry)) {
                    geometries.add(geometry);
                }
            }else {
                geometries.add(geometry);
            }
            i++;
        }
        System.out.println(i+"   相交 "+geometries.size());
        return geometries;
    }
    /**
     * 获取栅格化后的 BoundingBox 集合
     *
     * @param srcGeometry    栅格前的 geometry
     * @param srcBoundingBox 栅格前的 boundingBox
     * @return 栅格化后的 BoundingBox 集合
     * @throws Exception 异常
     */
    public List<BoundingBox> gridGeometry(Geometry srcGeometry, BoundingBox srcBoundingBox) throws Exception {

        System.out.println(JSONObject.toJSONString(srcBoundingBox));
        List<BoundingBox> boundingBoxes = new LinkedList<>();

//        FileDataStore dataStore = FileDataStoreFinder.getDataStore(url);
//        SimpleFeatureSource ozMapSource = dataStore.getFeatureSource();
//
//        // Set the grid size (1 degree) and create a bounding envelope
//        // that is neatly aligned with the grid size
//        double sideLen = 1.0;
//        ReferencedEnvelope gridBounds = Envelopes.expandToInclude(ozMapSource.getBounds(), sideLen);
//
//        // Create a feature type
//        SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
//        tb.setName("grid");
//        tb.add(
//                GridFeatureBuilder.DEFAULT_GEOMETRY_ATTRIBUTE_NAME,
//                Polygon.class,
//                gridBounds.getCoordinateReferenceSystem());
//        tb.add("id", Integer.class);
//        SimpleFeatureType TYPE = tb.buildFeatureType();
//
//        // Build the grid the custom feature builder class
//        GridFeatureBuilder builder = new IntersectionBuilder(TYPE, ozMapSource);
//        SimpleFeatureSource grid = Grids.createHexagonalGrid(gridBounds, sideLen, -1, builder);

        //获取栅格精度 (单位 度 °)
        double sideLen = getSideLen(srcBoundingBox);
        //获取 envelope
        ReferencedEnvelope envelope = getReferencedEnvelope(srcBoundingBox, sideLen);


        // max distance between vertices
        //double vertexSpacing = squareWidth / 20;

        //栅格化
        SimpleFeatureSource grid = Grids.createSquareGrid(envelope, sideLen);
        SimpleFeatureCollection features = grid.getFeatures();

        SimpleFeatureIterator iterator = features.features();
        while (iterator.hasNext()) {
            SimpleFeature feature = iterator.next();
            Geometry geometry = (Geometry) feature.getDefaultGeometry();

            //相交计算
            if (srcGeometry.intersects(geometry)) {
                DefaultBufferImpl  defaultBuffer= (DefaultBufferImpl) PoiTypeEnums.DEFAULT.getBufferUtil();
                BoundingBox bounds = feature.getBounds();
                boundingBoxes.add(bounds);
            }

        }
        return boundingBoxes;
    }

    //================================================= Gird ========================================================


    /**
     * 获取栅格化的 Envelope
     *
     * @param boundingBox 原 boundingBox
     * @param sideLen     栅格精度
     * @return Envelope
     */
    private ReferencedEnvelope getReferencedEnvelope(BoundingBox boundingBox, double sideLen) {
        double maxX = getDoubleValueUp(boundingBox.getMaxX(), sideLen);
        double maxY = getDoubleValueUp(boundingBox.getMaxY(), sideLen);
        double minX = getDoubleValueDown(boundingBox.getMinX(), sideLen);
        double minY = getDoubleValueDown(boundingBox.getMinY(), sideLen);
        return new ReferencedEnvelope(minX, maxX, minY, maxY, DefaultGeographicCRS.WGS84);
    }




    /**
     * 获取栅格精度值
     *
     * @param boundingBox box
     * @return 栅格精度 以 度 为单位
     */
    public static double getSideLen(BoundingBox boundingBox) {
        double maxX = boundingBox.getMaxX();
        double maxY = boundingBox.getMaxY();
        double minX = boundingBox.getMinX();
        double minY = boundingBox.getMinY();
        double xBetween = Math.abs(new BigDecimal(Double.toString(maxX)).subtract(new BigDecimal(Double.toString(minX))).doubleValue());
        double yBetween = Math.abs(new BigDecimal(Double.toString(maxY)).subtract(new BigDecimal(Double.toString(minY))).doubleValue());
        // SIDE_LEN_SIZE =  边长格网数 可根据实际情况自定义
        double SIDE_LEN_SIZE = 50000;
        double result = new BigDecimal(Double.toString(Math.min(xBetween, yBetween))).divide(new BigDecimal(SIDE_LEN_SIZE)).doubleValue();
        result = Math.max(result, 0.0014);
        return Double.parseDouble(String.format("%.4f", result));
    }

    /**
     * 获取栅格精度值
     *
     * @param boundingBox box
     * @return 栅格精度 以 度 为单位
     */
    public static double getSideLen(BoundingBox boundingBox,int sideLenSize) {
        double maxX = boundingBox.getMaxX();
        double maxY = boundingBox.getMaxY();
        double minX = boundingBox.getMinX();
        double minY = boundingBox.getMinY();
        double xBetween = Math.abs(new BigDecimal(Double.toString(maxX)).subtract(new BigDecimal(Double.toString(minX))).doubleValue());
        double yBetween = Math.abs(new BigDecimal(Double.toString(maxY)).subtract(new BigDecimal(Double.toString(minY))).doubleValue());
        String dataInfo= Double.toString(Math.min(xBetween, yBetween));
        // SIDE_LEN_SIZE =  边长格网数 可根据实际情况自定义
        String result = new BigDecimal(dataInfo).divide(new BigDecimal(sideLenSize),8,BigDecimal.ROUND_HALF_UP).toString();

        double resultInfo = Math.max(Double.valueOf(result), 0.0014);
        System.out.println(resultInfo);
        return Double.parseDouble(String.format("%.4f", resultInfo));
    }

    /**
     * 获取栅格精度值
     *
     * @return 栅格精度 以 度 为单位
     */
    public static double getSideLen(double max,double min,int sideLenSize) {
        String dataInfo= Double.toString(Math.min(min, max));
        BigDecimal bigDecimal= new BigDecimal(dataInfo).divide(new BigDecimal(sideLenSize),4,BigDecimal.ROUND_HALF_UP);
        double result = bigDecimal.doubleValue();
        result = Math.max(result, 0.0014);
        return Double.parseDouble(String.format("%.4f", result));
    }

    /**
     * 向上取值
     *
     * @param value   值
     * @param sideLen 栅格精度
     * @return 值
     */
    private double getDoubleValueUp(double value, double sideLen) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        nf.setRoundingMode(RoundingMode.UP);
        String format = nf.format(value);
        return Math.min(Double.parseDouble(format) + sideLen, 180);
    }

    /**
     * 向下取值
     *
     * @param value   值
     * @param sideLen 栅格精度
     * @return 值
     */
    private double getDoubleValueDown(double value, double sideLen) {
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        nf.setRoundingMode(RoundingMode.DOWN);
        String format = nf.format(value);
        return Math.max(Double.parseDouble(format) - sideLen, -180);
    }

}
